#include <gtest/gtest.h>
#include <unistd.h>
#include <string>

#include "tcpconnection.h"
#include "eventloop.h"
#include "channel.h"

// Dummy EventLoop 不做实际IO，覆盖 updateChannel 和 removeChannel
class DummyLoop : public EventLoop {
public:
    void updateChannel(Channel*)  {}
    void removeChannel(Channel*)  {}
};

TEST(TcpConnectionTest, BasicReadWrite) {
    int fds[2];
    ASSERT_EQ(pipe(fds), 0);

    EventLoop loop;
    auto conn = std::make_shared<TcpConnection>(&loop, fds[0]);

    std::string message;
    conn->setMessageCallback([&](const std::shared_ptr<TcpConnection>&, const std::string& buf) {
        message = buf;
    });

    // 写入一条消息
    const char* msg = "hello";
    write(fds[1], msg, strlen(msg));

    // 手动触发读事件
    conn->handleRead();

    ASSERT_EQ(message, "hello");

    close(fds[0]);
    close(fds[1]);
}

TEST(TcpConnectionTest, HandleReadClose) {
    DummyLoop loop;

    int fds[2];
    ASSERT_EQ(pipe(fds), 0);

    TcpConnection conn(&loop, fds[0]);

    // 关闭写端，读端读取时返回0，触发shutdown
    close(fds[1]);

    // 触发读事件
    conn.handleRead();

    // fd已关闭，再读应返回错误
    // 这里不验证直接检查是否关闭了 fd
    // 触发shutdown后fd应被close
    // 该fd无效后系统会返回错误
}

